<template>
	<div class="content">
		<div class="pageTableView">
			<div class="pageTableMenuView">
				<div class="pageTableTitle"> 工单信息</div>
				<div class="pageTableButView">
					<el-button @click="goBack" :icon="ArrowLeft">返回</el-button>
				</div>
			</div>
			<el-row :gutter="16" style="margin-bottom: 20px;">
				<el-col :span="8">
					<div>工序订单：{{ titleDetail.no || '--' }}</div>
				</el-col>
				<el-col :span="8">
					<div>产品名称：{{ titleDetail.productName || '--' }}</div>
				</el-col>
				<el-col :span="8">
					<div>总数：{{ titleDetail.orderCount || '--' }}</div>
				</el-col>
			</el-row>
			<el-row :gutter="16">
				<el-col :span="8">
					<div>开始时间：{{ titleDetail.planBeginTime || '--' }}</div>
				</el-col>
				<el-col :span="8">
					<div>结束时间：{{ titleDetail.planEndTime || '--' }}</div>
				</el-col>
				<el-col :span="4">
					<div>待派发：{{ titleDetail.unfinishedCount || 0 }}</div>
				</el-col>
				<el-col :span="4">
					<div>已派发：{{ titleDetail.distributeCount || 0 }}</div>
				</el-col>
			</el-row>
		</div>
		<div class="pageTableView">
			<div class="pageTableMenuView">
				<div class="pageTableTitle">列表信息
					<el-icon>
						<house-icon />
					</el-icon>
				</div>
				<div class="pageTableButView">
					<el-button :icon="Plus" @click="handleAdd" type="primary">批量派工</el-button>
				</div>
			</div>
			<div :style="400">
				<el-table :data="orderList" :height="tableHeight" border stripe>
					<el-table-column prop="workNo" label="工序订单号" align="center"></el-table-column>
					<el-table-column prop="productName" label="产品名称" align="center"></el-table-column>
					<el-table-column prop="equipmentName" label="设备名称" align="center"></el-table-column>
					<!-- <el-table-column prop="productName" label="产品名称" align="center"></el-table-column> -->
					<el-table-column prop="orderCount" label="订单数量" align="center"></el-table-column>
					<el-table-column label="状态" align="center">
						<template #default="{ row }"> {{ dicData.find(i => i.value === row.status)?.label }}</template>
					</el-table-column>
					<el-table-column label="操作" align="center" fixed="right" width="180">
						<template #default="{ row }">
							<el-button size="small" :icon="Edit" @click="handleDeleteRow(row, true)" :disabled="row.status > 2">下发
							</el-button>
							<el-button size="small" type="danger" :icon="Delete" @click="handleDeleteRow(row)"
												 :disabled="row.status > 2">删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<div class="pagePagination">
				<el-pagination background layout="prev, pager, next, jumper, sizes, total" :total="total"
											 :page-size="params.pageSize" :current-page="params.current" @size-change="changePageSize"
											 @current-change="changePageNum"></el-pagination>
			</div>
		</div>
		<CreateOrUpdateModal :visible="createStatus" :form="form" title="批量派工" @update:visible="createStatus = $event"
												 :handleAddSubmit="handleAddSubmit" :materialList="materialList"
												 :putMaterialData="putMaterialData"
												 :equipmentData="equipmentData" :titleDetail="titleDetail" :handleClose="handleClose"
												 @update:putMaterialData="putMaterialData = $event" />
	</div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
	procedureResourceApi,
	equipmentAll,
	putMaterialRedord,
	basedataWorkOrderUpdate,
	procedureOrder,
	procedureOrderDataApi,
	delBasedataWorkOrder
} from '@/api/scheduling/dispatchManagement';
import { Edit, Delete, Plus, ArrowLeft } from '@element-plus/icons-vue';
import CreateOrUpdateModal from './modalOpen.vue';
import axiosInstance from '@/utils/http/api';
import { useRoute } from 'vue-router';

const route = useRoute();
const params = ref({
	pageSize: 20,
	current: 1
});

const dicData = ref([
	{ label: '新建', value: 0 },
	{ label: '待排产', value: 1 },
	{ label: '已排产', value: 2 },
	{ label: '下发', value: 3 },
	{ label: '开工', value: 4 },
	{ label: '中断', value: 5 },
	{ label: '暂停', value: 6 },
	{ label: '完成', value: 7 }
]);


const importExcelState = ref(false);
const orderList = ref([]);
const total = ref(0);
const deleteShow = ref(false);
const currentItem = ref({});
const createStatus = ref(false);
const form = ref({});
const materialList = ref([]);
const titleDetail = ref({});
const putMaterialData = ref([]);
const equipmentData = ref([]);

const tableHeight = computed(() => window.innerHeight - 400);

onMounted(() => {
	getList();
	relevance();

	// procedureOrderDataApi({
	//   id: route.query.id
	// }).then(res => {
	//   if (res.code === 200) {
	//     titleDetail.value = res.data.records[0];
	//   }
	// });


});

const relevance = () => {
	equipmentAll().then(res => {
		if (res.code === 200) {
			equipmentData.value = res.data;
		}
	});
};

const router = useRouter();

const handleClose = () => {
	createStatus.value = false;

};

const getList = () => {
	procedureOrder({
		...params.value,
		id: route.query.id
	}).then(res => {
		if (res.code === 200) {
			orderList.value = res.data;
			total.value = res.data.total;
		}
	});

	axiosInstance.post('/api/planProcedureOrder/queryById', { id: route.query.id })
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			titleDetail.value = res.data;
		});
};

const reset = () => {
	params.value = { pageSize: 20, current: 1 };
	getList();
};

const goBack = () => {
	router.go(-1);
};

const changeNum = () => {
	params.value.current = 1;
	params.value.pageSize = 20;
	getList();
};

const handleAdd = () => {
	putMaterialData.value = [{
		needNumber: 0,
		equipmentId: '',
		toolId: ''
	}];
	form.value = {};
	createStatus.value = true;
};

const handleImportData = () => {
	importExcelState.value = true;
};

const handleAddSubmit = () => {
	let number = 0;
	const promises = [];
	console.log(putMaterialData.value, 'putMaterialData.value');
	for (const item of putMaterialData.value) {
		promises.push({
			equipmentId: item.equipmentId,
			orderCount: item.needNumber,
			procedureOrderId: route.query.id,
			toolingId: item.toolId
			// equipmentToolDTO: {
			//   equipmentId: item.equipmentId,
			//   toolId: item.toolId
			// }
		});
		number = number + item.needNumber;
	}
	//   putMaterialData.value.map(item => (
	//       promises.push({
	//         equipmentId: item.equipmentId,
	//         orderCount: item.needNumber,
	//         procedureId: route.query.id,
	//         toolingId: item.toolId
	//         // equipmentToolDTO: {
	//         //   equipmentId: item.equipmentId,
	//         //   toolId: item.toolId
	//         // }
	//       })
	//
	//
	// ))

	if (Number(number) > Number(titleDetail.value.unfinishedCount)) {
		ElMessage.warning('已超出待派发数量');
		return false;
	}
	putMaterialRedord(promises).then(res => {
		if (res.code === 200) {
			ElMessage.success('保存成功');
			getList();
			createStatus.value = false;
		} else {
			ElMessage.error(res.message);
		}
	});
};


const handleDeleteRow = (row, flag) => {
	if (flag) {
		ElMessageBox.confirm('是否要下发？', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'success'
		}).then(async () => {
			currentItem.value = { ...row, open: flag };
			basedataWorkOrderUpdate([{ id: row.id, status: 3, equipmentId: row.equipmentId }]).then(res => {
				if (res.code != 200) {
					ElMessage.error(res.message);
					return false;
				}
				ElMessage.success('下发成功');
				getList();
			});
		}).catch(() => {
		});
		return;
	}
	ElMessageBox.confirm('是否要删除？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'error'
	}).then(async () => {
		currentItem.value = { ...row, open: flag };
		handleDeleteSure();
	}).catch(() => {
	});

};

const handleDeleteSure = () => {
	delBasedataWorkOrder({ ids: [currentItem.value.id] }).then(res => {
		if (res.code !== 200) {
			ElMessage.warning(res.message);
			return false;
		}
		ElMessage.success('删除成功');
		deleteShow.value = false;
		getList();
	});
};

const changePageNum = (val) => {
	params.value.current = val;
	getList();
};

const changePageSize = (val) => {
	params.value.pageSize = val;
	getList();
};
</script>
